#!/bin/bash

BL_TOOLS_DIR=${PWD}/device/mediatek/common/tools/bootloader
DTC_TOOLS_DIR=${PWD}/prebuilts/gcc/linux-x86/aarch64/aarch64-poky-linux/x86_64-oesdk-linux/usr/bin
GLOBAL_OUT_DIR=${PWD}/out/target/product/$3/rawinfo
GLOBAL_KEY_HASH_FILE="${GLOBAL_OUT_DIR}/efuse_key_hash.tmp"

EFUSE_HASH_CELL=("20040000" "21040000" "22040000" "23040000" "24040000" "25040000" "26040000" "27040000")
EFUSE_CELL_INDEX=0

echo_hex()
{
	# Check parameter number
	if [ 1 -ne $# ]; then
		return 1
	fi

	# Check whether parameter is hex string
	if ! (echo $1 | grep '^[0-9A-Fa-f]\+$') >/dev/null 2>&1; then
		return 2
	fi

	local CHAR_NUM=`echo -n $1 | wc -c`
	# Check char number of hex string
	if [ 0 -ne $((${CHAR_NUM} % 2)) ]; then
		return 3
	fi
	echo -en "`echo $1 | sed 's/../\\\x&/g'`"
}

split_str_to_quadbytes() {
        quadbytes=""
        sed_cmd="sed s,\(..\)\(..\)\(..\)\(..\),\1\2\3\4,g"
        if [ ! -z "$1" ]; then
            for i in $(seq 1 8 ${#1}); do
                    end_idx=`echo "${i} + 7" | bc`
                    qb=$(echo ${1} | cut -c${i}-${end_idx} | ${sed_cmd})
                    qb=${EFUSE_HASH_CELL[$((EFUSE_CELL_INDEX++))]}${qb}
                    quadbytes="${quadbytes}${qb}"
            done
        fi

        echo -n $quadbytes
}

gen_sbc_key_hash() {
        FDT_IMG=$1
        TMP_FILE=$(mktemp col_rgn.bin.XXXXXX)

        DEF_CONF=`${DTC_TOOLS_DIR}/fdtget -t s ${FDT_IMG} /configurations default`
        SIG_NODE=`${DTC_TOOLS_DIR}/fdtget -l ${FDT_IMG} /configurations/${DEF_CONF}`
        KEY_HINT=`${DTC_TOOLS_DIR}/fdtget -t s ${FDT_IMG} /configurations/${DEF_CONF}/${SIG_NODE} key-name-hint`
        SHAX=`${DTC_TOOLS_DIR}/fdtget -t s ${FDT_IMG} /configurations/${DEF_CONF}/${SIG_NODE} algo | cut -d, -f1`
        ${BL_TOOLS_DIR}/security/fit-lk/extract_region ${FDT_IMG} ${TMP_FILE} /signature/key-${KEY_HINT} >/dev/null 2>&1
        KEY_HASH=`${SHAX}sum ${TMP_FILE} | cut -d " " -f 1`

        echo -n "$(split_str_to_quadbytes ${KEY_HASH})" > ${GLOBAL_KEY_HASH_FILE};rm -f ${TMP_FILE}
}

gen_sbc_key_hash $2
echo_hex "$(cat ${GLOBAL_KEY_HASH_FILE})" > "${GLOBAL_OUT_DIR}/eFusedata_hex.tmp"
dd if=$1 of=${GLOBAL_OUT_DIR}/eFusedata_before_hash bs=8 count=1 >/dev/null 2>&1;dd if=$1 of=${GLOBAL_OUT_DIR}/eFusedata_after_hash bs=1 skip=72 >/dev/null 2>&1
cat "${GLOBAL_OUT_DIR}/eFusedata_hex.tmp" >> "${GLOBAL_OUT_DIR}/eFusedata_before_hash";cat "${GLOBAL_OUT_DIR}/eFusedata_after_hash" >> "${GLOBAL_OUT_DIR}/eFusedata_before_hash"
mv "${GLOBAL_OUT_DIR}/eFusedata_before_hash" "${GLOBAL_OUT_DIR}/eFusedata";rm ${GLOBAL_OUT_DIR}/eFusedata_after_hash ${GLOBAL_KEY_HASH_FILE} ${GLOBAL_OUT_DIR}/eFusedata_hex.tmp
